<template>
  <div class="set-range" v-loading="loading">
    <div class="block">
      <div class="title">数据范围</div>
      <div class="row district-row">
        <!-- <div
          class="item"
          v-if="
            isEditMode ||
            !(
              accountDistrict.level >= 1 &&
              accountDistrict.province_list.length === 1
            )
          "
        >
          <div class="label">省</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.province_list"
              placeholder="选择省份"
              value-key="F_id"
              @change="changeProvinceList"
              :disabled="isAutoFilledBySchoolId || isEditMode"
            >
              <el-option
                v-for="item in accountDistrict.province_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div> -->
        <div
          class="item"
          v-if="
            isEditMode ||
            !(
              accountDistrict.level >= 2 &&
              accountDistrict.city_list.length === 1
            )
          "
        >
          <div class="label">市</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.city_list"
              placeholder="选择城市"
              value-key="F_id"
              @change="changeCityList"
              :disabled="isAutoFilledBySchoolId || isEditMode"
            >
              <el-option
                v-for="item in accountDistrict.city_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div
          class="item"
          v-if="
            isEditMode ||
            !(
              accountDistrict.level >= 3 &&
              accountDistrict.county_list.length === 1
            )
          "
        >
          <div class="label">区（县）</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.county_list"
              placeholder="选择区（县）"
              value-key="F_id"
              @change="changeCountyList"
              :disabled="isAutoFilledBySchoolId || isEditMode"
            >
              <el-option
                v-for="item in accountDistrict.county_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div
          class="item"
          v-if="
            isEditMode ||
            !(
              accountDistrict.level >= 4 &&
              accountDistrict.school_list.length === 1
            )
          "
        >
          <div class="label">学校</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.school_list"
              placeholder="选择学校"
              value-key="F_id"
              :disabled="isAutoFilledBySchoolId || isEditMode"
            >
              <el-option
                v-for="item in accountDistrict.school_list"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="row school-info-row">
        <div class="item" v-if="showGradeList">
          <div class="label">年级</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.grade_list"
              placeholder="选择年级"
              value-key="id"
            >
              <el-option
                v-for="item in gradeList"
                :key="'grade_' + item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="item" v-if="classList.length">
          <div class="label">班级</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.class_list"
              placeholder="选择班级"
              value-key="F_id"
            >
              <el-option
                v-for="item in classList"
                :key="item.F_id"
                :label="item.F_name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="item">
          <div class="label">科目</div>
          <div class="data">
            <el-select
              multiple
              collapse-tags
              v-model="newDistrict.subject_list"
              placeholder="选择科目"
              value-key="id"
            >
              <el-option
                v-for="item in subjectList"
                :key="'subject_' + item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex';
import { subjectList } from '@/utils/maps';
export default {
  name: 'setRange',
  props: {
    type: Number,
    checkedRoleList: {
      type: Array,
      required: false,
      default: () => []
    },
  },
  components: {},
  data() {
    return {
      loading: false,
      // 这里保存的是当前登录账号的数据范围
      accountDistrict: {
        province_list: [],
        city_list: [],
        county_list: [],
        school_list: [],
        grade_list: [],
        class_list: [],
        subject_list: [],
        stage: 0,
        level: 1,
      },

      // 这里保存的是新成员的已选的数据范围
      newDistrict: {
        province_list: [],
        city_list: [],
        county_list: [],
        school_list: [],
        grade_list: [],
        class_list: [],
        subject_list: [],
        stage: 0,
        level: 1,
      },
      level: 1,
      options: {},
      // gradeList: [],
      // subjectList: [],
      // showClassList: false,
      schoolGradeClass: [], // 当前学校的年级、班级 tree 结构
      schoolSubjectList: [],
      commonGradeList: [],
      commonSubjectList: [],
      showGradeList: true,
      _lastSchoolId: null, // 记录上次请求的学校ID，用于防止重复调用
      isAutoFilledBySchoolId: false, // 标记是否根据 schoolId 自动填充，如果是则不允许修改省市区学校
    };
  },
  async mounted() {
    this.getCommonGradeAndSubject();
    // 初始化时设置监听器
    this.setWachter();
  },
  watch: {
    async type(newVal, oldVal) {
      // 避免初始化时触发（oldVal 为 undefined 时）
      if (oldVal === undefined && newVal !== undefined) {
        // 首次设置 type，需要初始化
        await this.getAccountDistrict();
        this.getNewDistrict();
      } else if (oldVal !== undefined && newVal !== oldVal) {
        // type 值发生变化时才重新加载
        await this.getAccountDistrict();
        this.getNewDistrict();
      }
    },
    'accountDistrict.province_list': {
      async handler(v) {
        if (v.length === 1) {
          if (!this.accountDistrict.city_list.length) {
            this.accountDistrict.city_list = await this.getDistricts(v[0].F_id);
          }
        }
      },
    },
    'accountDistrict.city_list': {
      async handler(v) {
        if (v.length === 1) {
          if (!this.accountDistrict.county_list.length) {
            this.accountDistrict.county_list = await this.getDistricts(
              v[0].F_id
            );
          }
        }
      },
    },
    'accountDistrict.county_list': {
      async handler(v) {
        if (v.length === 1) {
          if (!this.accountDistrict.school_list.length) {
            this.accountDistrict.school_list = await this.getDistrictSchools({
              F_page: 0,
              F_area_id: v[0].F_id,
            });
          }
        }
      },
    },
    'newDistrict.school_list': {
      handler(newValue, oldValue) {
        // 避免初始化时触发（oldValue 为 undefined 时，或者新旧值都是空数组）
        if (oldValue === undefined) {
          // 初始化时不触发，除非初始化时就有学校数据
          if (newValue && newValue.length > 0) {
            this.newDistrict.level = 4;
            if (newValue.length === 1) {
              this.getSchoolClasses();
            }
          }
          return;
        }
        
        // 如果新旧值都是空数组，不触发
        if (Array.isArray(oldValue) && oldValue.length === 0 && 
            Array.isArray(newValue) && newValue.length === 0) {
          return;
        }
        
        // 如果学校列表被清空，清空相关数据
        if (!newValue || newValue.length === 0) {
          this.schoolGradeClass = [];
          this.schoolSubjectList = [];
          this._lastSchoolId = null;
          if (this.newDistrict.county_list.length) {
            this.newDistrict.level = 3;
          }
          return;
        }
        
        // 学校列表有变化时才处理
        this.schoolGradeClass = [];
        this.newDistrict.level = 4;
        if (newValue.length === 1) {
          this.getSchoolClasses();
        }
      },
    },

    checkedRoleList(v) {
      if(v.find(e => e.F_role_name === '科组长')) {
        this.newDistrict.grade_list = [];
      }
      this.showGradeList = !v.find(e => e.F_role_name === '科组长')
    },
  },
  computed: {
    ...mapState('user', ['userInfo']),
    ...mapGetters('user', ['isSuperAdmin', 'userPermission']),
    // 判断是否是编辑模式：检查 sessionStorage 中是否有 edit_user_info 且包含 F_district 或 F_describe
    isEditMode() {
      try {
        const editUserInfo = JSON.parse(sessionStorage.getItem('edit_user_info') || '{}');
        // 如果有 edit_user_info 且包含 F_district 或 F_describe，说明是编辑模式
        return editUserInfo && Object.keys(editUserInfo).length > 0 && 
               (editUserInfo.F_district || editUserInfo.F_describe);
      } catch (e) {
        return false;
      }
    },
    classList() {
      if (this.newDistrict.grade_list.length !== 1) {
        return [];
      } else {
        const gradeId = this.newDistrict.grade_list[0].id;
        const grade = this.schoolGradeClass.find((e) => e.F_grade === gradeId);
        return grade ? grade.F_classes : [];
      }
    },
    gradeList() {
      if (this.newDistrict.school_list.length !== 1) {
        return this.commonGradeList;
      }
      return this.schoolGradeClass
        .map((e) => {
          const grade = this.$maps.gradeList.find((u) => u.id === e.F_grade);
          if (grade) {
            return { id: e.F_grade, name: grade.name };
          }
        })
        .sort((a, b) => a.id - b.id);
    },
    subjectList() {
      if (this.newDistrict.school_list.length !== 1) {
        return this.commonSubjectList;
      }
      return this.schoolSubjectList;
    },
  },
  methods: {
    async getAccountDistrict() {
      // 获取最大数据范围
      if (!this.isSuperAdmin) {
        this.accountDistrict = JSON.parse(JSON.stringify(this.userPermission));
      } else {
        // 是超管，给它最大数据范围就好了
        // 注意：设置 level 为 1 会让省下拉框隐藏（如果只有一个省），所以不设置 level
        // 或者设置为 0，让所有下拉框都显示
        this.accountDistrict.level = 0; // 设置为 0，让所有下拉框都显示
        this.accountDistrict.province_list = await this.getDistricts(0);
      }
    },
    // 根据 schoolId 从 rb_school 表获取区县和学校信息
    async initDistrictBySchoolId(schoolId) {
      if (!schoolId) {
        return;
      }
      
      try {
        // 获取学校信息
        const { F_school } = await this.$api.getSchool({ F_school_id: schoolId });
        if (!F_school || !F_school.F_loc) {
          return;
        }
        
        const { F_prov_id, F_prov_name, F_city_id, F_city_name, F_district_id, F_district_name } = F_school.F_loc;
        
        // 获取省市区信息
        const provinceList = await this.getDistricts(0);
        const cityList = await this.getDistricts(F_prov_id);
        const countyList = await this.getDistricts(F_city_id);
        
        // 设置 accountDistrict 的省市区信息
        // 注意：设置 accountDistrict.level 为 0，确保所有下拉框都能显示和修改
        // 如果设置为较高的 level（如 3 或 4），当对应列表长度为 1 时，下拉框会被隐藏
        this.accountDistrict.province_list = provinceList;
        this.accountDistrict.city_list = cityList;
        this.accountDistrict.county_list = countyList;
        this.accountDistrict.level = 0; // 设置为 0，让所有下拉框都显示，允许用户修改
        
        // 根据区县ID获取学校列表
        const schoolList = await this.getDistrictSchools({
          F_page: 0,
          F_area_id: F_district_id,
        });
        this.accountDistrict.school_list = schoolList;
        
        // 设置 newDistrict 的省市区和学校信息（预填充，但允许用户修改）
        this.newDistrict.province_list = provinceList.filter(p => p.F_id === F_prov_id);
        this.newDistrict.city_list = cityList.filter(c => c.F_id === F_city_id);
        this.newDistrict.county_list = countyList.filter(c => c.F_id === F_district_id);
        // 确保学校信息包含完整的学校对象，支持字符串和数字类型的 schoolId 比较
        const selectedSchool = schoolList.find(s => {
          const sId = s.F_id || s.id;
          return sId === schoolId || String(sId) === String(schoolId);
        });
        if (selectedSchool) {
          this.newDistrict.school_list = [selectedSchool];
        } else if (F_school) {
          // 如果学校列表中找不到，使用从 getSchool 获取的学校信息
          this.newDistrict.school_list = [F_school];
        } else {
          this.newDistrict.school_list = [];
        }
        // 设置 newDistrict.level 为学校级别，表示已选择到学校级别
        this.newDistrict.level = 4; // 学校级别
        
        // 标记为根据 schoolId 自动填充，不允许用户修改省市区学校
        this.isAutoFilledBySchoolId = true;
        
        console.log('根据 schoolId 初始化数据范围:', {
          schoolId,
          province: F_prov_name,
          city: F_city_name,
          district: F_district_name,
          school: F_school.F_name
        });
      } catch (error) {
        console.error('根据 schoolId 获取学校信息失败:', error);
        this.isAutoFilledBySchoolId = false; // 出错时重置标志
      }
    },
    
    getNewDistrict() {
      // 重置自动填充标志，允许用户修改
      this.isAutoFilledBySchoolId = false;
      
      const levelNameList = [
        'province_list',
        'city_list',
        'county_list',
        'school_list',
        'grade_list',
        'class_list',
        'subject_list',
      ];
      const editUserInfo = JSON.parse(sessionStorage.getItem('edit_user_info') || '{}');
      if (editUserInfo && Object.keys(editUserInfo).length > 0) {
        // 当前是编辑页面
        // 优先使用 F_district，如果没有则使用 F_describe（兼容旧数据）
        const districtStr = editUserInfo.F_district || editUserInfo.F_describe || '';
        if (!districtStr) {
          // 如果区域信息为空，初始化所有列表为空
          this.newDistrict = {
            province_list: [],
            city_list: [],
            county_list: [],
            school_list: [],
            grade_list: [],
            class_list: [],
            subject_list: [],
            stage: 0,
            level: 1,
          };
          return;
        }
        let userRange;
        try {
          userRange = JSON.parse(districtStr);
        } catch (e) {
          console.error('解析数据范围失败:', e);
          this.newDistrict = {
            province_list: [],
            city_list: [],
            county_list: [],
            school_list: [],
            grade_list: [],
            class_list: [],
            subject_list: [],
            stage: 0,
            level: 1,
          };
          return;
        }
        for (let [k, v] of Object.entries(userRange)) {
          if (k !== 'level' && k !== 'stage' && !Array.isArray(v)) {
            userRange[k] = [];
          }
        }
        // 确保 stage 字段存在且为数字类型
        if (userRange.stage === undefined || userRange.stage === null) {
          userRange.stage = 0;
        } else if (Array.isArray(userRange.stage)) {
          userRange.stage = 0;
        } else {
          userRange.stage = Number(userRange.stage) || 0;
        }
        // 确保所有必需的字段都存在
        this.newDistrict = {
          province_list: userRange.province_list || [],
          city_list: userRange.city_list || [],
          county_list: userRange.county_list || [],
          school_list: userRange.school_list || [],
          grade_list: userRange.grade_list || [],
          class_list: userRange.class_list || [],
          subject_list: userRange.subject_list || [],
          stage: userRange.stage,
          level: userRange.level !== undefined ? Number(userRange.level) : 1,
        };

        // 在省市区学校这前4个层级,又需要把newDistrict的这些列表复制给accountDistrict
        for (
          let i = this.accountDistrict.level;
          i < this.newDistrict.level;
          i++
        ) {
          this.accountDistrict[levelNameList[i]] = JSON.parse(
            JSON.stringify(this.newDistrict[levelNameList[i]])
          );
        }
        
        // 编辑模式下，如果有学校信息，需要加载班级数据以便回显
        if (this.newDistrict.school_list && this.newDistrict.school_list.length > 0) {
          // 使用 $nextTick 确保在数据设置完成后再加载班级数据
          this.$nextTick(async () => {
            await this.getSchoolClasses();
          });
        }
      } else {
        // 添加用户时, 登录账号的最低级别列表是多个值时, 要让新用户的初始状态最低层级是没有选中的
        this.newDistrict = JSON.parse(JSON.stringify(this.accountDistrict));
        const level = this.newDistrict.level;
        if (this.newDistrict[levelNameList[level - 1]].length >= 2) {
          this.newDistrict[levelNameList[level - 1]] = [];
          this.newDistrict.level = level - 1;
        }
      }
    },
    setWachter() {
      // 监听年级变化，如果年级变化则清空班级（但保留编辑时已加载的班级数据）
      this.$watch(
        () => {
          return this.newDistrict.grade_list;
        },
        (newVal, oldVal) => {
          // 只有在年级真正变化时才清空班级（避免初始化时清空）
          if (oldVal !== undefined && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
            this.newDistrict.class_list = [];
          }
        }
      );
      // 监听学校变化，如果学校变化则清空班级（但保留编辑时已加载的班级数据）
      this.$watch(
        () => {
          return this.newDistrict.school_list;
        },
        (newVal, oldVal) => {
          // 只有在学校真正变化时才清空班级（避免初始化时清空）
          if (oldVal !== undefined && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
            this.newDistrict.class_list = [];
          }
        }
      );
    },
    async getDistricts(areaId) {
      this.loading = true;
      const { F_districts } = await this.$api.getDistricts2({
        F_parent_id: areaId,
      });
      this.loading = false;
      return F_districts || [];
    },
    // 获取某个区下的学校列表, 部分也
    async getDistrictSchools(params) {
      this.loading = true;
      const res = await this.$api.getSchools(params);
      this.loading = false;
      return res.F_schools || [];
    },
    getCommonGradeAndSubject() {
      this.commonGradeList = [];
      this.commonSubjectList = [];
      const { gradeList } = this.$maps;
      this.commonGradeList = JSON.parse(JSON.stringify(gradeList));
      this.commonSubjectList = JSON.parse(JSON.stringify(subjectList));
    },
    async changeProvinceList(val) {
      if (val.length === 0) this.newDistrict.level = 0;
      else this.newDistrict.level = 1;
      this.newDistrict.city_list = [];
      this.newDistrict.county_list = [];
      this.newDistrict.school_list = [];
      this.accountDistrict.city_list = [];
      this.accountDistrict.county_list = [];
      this.accountDistrict.school_list = [];
      if (val.length === 1) {
        this.accountDistrict.city_list = await this.getDistricts(val[0].F_id);
      }
    },
    async changeCityList(val) {
      if (val.length === 0) this.newDistrict.level = 1;
      else this.newDistrict.level = 2;
      this.newDistrict.county_list = [];
      this.newDistrict.school_list = [];
      this.accountDistrict.county_list = [];
      this.accountDistrict.school_list = [];
      if (val.length === 1) {
        this.accountDistrict.county_list = await this.getDistricts(val[0].F_id);
      }
    },
    async changeCountyList(val) {
      if (val.length === 0) this.newDistrict.level = 2;
      else this.newDistrict.level = 3;
      this.newDistrict.school_list = [];
      this.accountDistrict.school_list = [];
      // this.resetBehindLevel();
      if (val.length === 1) {
        this.accountDistrict.school_list = await this.getDistrictSchools({
          F_page: 0,
          F_area_id: val[0].F_id,
        });
      }
    },
    // 对某一级的多选项进行了操作，则清空其后面所有级别的可选列表、已选列表
    async resetBehindLevel() {
      console.log('reset');
      const list = [
        'province_list', // 0
        'city_list', // 1
        'county_list', // 2
        'school_list', // 3
      ];
      console.log(this.newDistrict.level);
      for (let i = this.newDistrict.level; i < list.length; i++) {
        // 清空后面所有层级的选中项和可选项
        this.newDistrict[list[i]] = [];
        this.accountDistrict[list[i]] = [];
      }
    },
    async getSchoolClasses() {
      if (!this.newDistrict.school_list || this.newDistrict.school_list.length === 0) {
        return;
      }
      
      const currentSchoolId = this.newDistrict.school_list[0].F_id;
      
      // 防止重复调用：如果已经有数据且学校ID相同，则不重复请求
      // 但如果是编辑模式且班级数据已存在，仍然需要加载以确保 classList 计算属性能正确工作
      const hasClassList = this.newDistrict.class_list && this.newDistrict.class_list.length > 0;
      if (this.schoolGradeClass.length > 0 && 
          this.schoolSubjectList.length > 0 && 
          this._lastSchoolId === currentSchoolId &&
          !hasClassList) {
        return;
      }
      
      // 记录当前学校ID
      this._lastSchoolId = currentSchoolId;
      
      const { F_grades = [], F_subjects = [] } =
        await this.$api.getSchoolClasses({
          F_school_id: currentSchoolId,
        });
      const list = await this.$api.getSchoolSubject(currentSchoolId);
      (F_grades || []).forEach((grade) => {
        // 班级排序
        grade.F_classes = grade.F_classes.sort((a, b) => {
          return a.F_index - b.F_index;
        });
      });
      this.schoolGradeClass = F_grades;
      this.schoolSubjectList = list;
    },
  },
};
</script>

<style lang="less" scoped>
.block {
  margin: 20px 0;
  .title {
    display: flex;
    align-items: center;
    font-size: 20px;
    font-weight: bold;
    padding: 10px 0 20px;
    &:before {
      content: '';
      display: inline-block;
      margin-right: 10px;
      width: 8px;
      height: 24px;
      background-color: #009cff;
    }
  }
  .row {
    display: flex;
    margin-bottom: 15px;
    .item {
      padding-right: 40px;
      .label {
        font-weight: bold;
        padding-bottom: 10px;
        i {
          color: #ff1900;
        }
      }
    }
  }
  .district-row {
    .item {
      width: 300px;
      .el-select {
        width: 100%;
      }
    }
  }
  .school-info-row {
    .item {
      width: 200px;
    }
  }
}
</style>
